import { CanvasContext } from "./designType";

export class Dimension {
  public originX?: number;
  public originY?: number;
  constructor(
    public length: number,        // 长度
    public width: number,         // 宽度
    public depth: number,        // 高度或深度
    public unit: 'mm' | 'cm' | 'm' = 'mm'  // 单位，默认为毫米
  ) { }

  setStartPoint(originX: number, originY: number) {
    this.originX = originX;
    this.originY = originY;


  }

  // 计算实际面积（假设长方形）
  calculateArea(): number {
    return this.length * this.width;
  }

  // 计算体积
  calculateVolume(): number {
    return this.length * this.width * this.depth;
  }
  // 绘制尺寸标注
  draw(ctx: CanvasContext): void {
    ctx.font = "14px Arial";
    ctx.fillStyle = "#000";
    ctx.strokeStyle = "#000";
    ctx.lineWidth = 1;

    // 绘制水平和垂直的尺寸标注
    if (this.originX && this.originY) {
      this.drawHorizontalDimension(ctx, this.originX, this.originY, this.length, this.unit);
      this.drawVerticalDimension(ctx, this.originX, this.originY, this.width, this.unit);

    }

  }

  // 绘制水平尺寸标注
  private drawHorizontalDimension(
    ctx: CanvasContext,
    x: number,
    y: number,
    length: number,
    unit: string
  ): void {
    const offset = 15;

    // 绘制水平尺寸线
    ctx.beginPath();
    ctx.moveTo(x, y - offset);
    ctx.lineTo(x + length, y - offset);
    ctx.stroke();

    // 绘制箭头
    // this.drawArrow(ctx, x, y - offset, x, y - offset);
    this.drawArrow(ctx, x, y - offset, x + length, y - offset);

    // 标注尺寸数值
    ctx.fillText(`${Math.floor(length*10)}${unit}`, x + length / 2 - 10, y - offset - 5);
    this.addInteractiveShape("dimension", `horizontal-${this.originX}-${this.originY}`, {
      x: textX,
      y: textY - 14, // 假设文本高度为 14
      width: ctx.measureText(text).width,
      height: 14,
    });
  }

  // 绘制垂直尺寸标注
  private drawVerticalDimension(
    ctx: CanvasContext,
    x: number,
    y: number,
    width: number,
    unit: string
  ): void {
    const offset = 15;

    // 绘制垂直尺寸线
    ctx.beginPath();
    ctx.moveTo(x - offset, y);
    ctx.lineTo(x - offset, y + width);
    ctx.stroke();

    // 绘制箭头
    this.drawArrow(ctx, x - offset, y, x - offset, y + width);
    // this.drawArrow(ctx, x - offset, y, x - offset, y);

    // 标注尺寸数值
    ctx.fillText(`${Math.floor(width*10)}${unit}`, x - offset - 25, y + width / 2);
  }

  // 绘制箭头
  private drawArrow(
    ctx: CanvasContext,
    x1: number,
    y1: number,
    x2: number,
    y2: number
  ): void {
    const headLength = 8; // 箭头的长度
    const angle = Math.atan2(y2 - y1, x2 - x1);

    // 绘制箭头终点
    ctx.beginPath();
    ctx.moveTo(x2, y2);
    ctx.lineTo(x2 - headLength * Math.cos(angle - Math.PI / 6), y2 - headLength * Math.sin(angle - Math.PI / 6));
    ctx.lineTo(x2 - headLength * Math.cos(angle + Math.PI / 6), y2 - headLength * Math.sin(angle + Math.PI / 6));
    ctx.lineTo(x2, y2);
    ctx.closePath();
    ctx.fill();
  }
}
